package cn.itcast.account.service.impl;

import cn.itcast.account.entity.AccountFreeze;
import cn.itcast.account.mapper.AccountFreezeMapper;
import cn.itcast.account.mapper.AccountMapper;
import cn.itcast.account.service.AccountService;
import cn.itcast.account.service.AccountTccService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountTccServiceImpl implements AccountTccService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private AccountFreezeMapper accountFreezeMapper;


    @Override
    @Transactional
    public void tryTcc(String userId, Integer money) {


        // 获取 xid
        String xid = RootContext.getXID();

        AccountFreeze accountFreeze = accountFreezeMapper.selectById(xid);
        if (accountFreeze != null){
            return;
        }

        // 1、 新增 account_freeze 冻结金钱
        accountFreeze = new AccountFreeze();
        accountFreeze.setXid(xid);
        accountFreeze.setFreezeMoney(money);
        accountFreeze.setState(AccountFreeze.State.TRY);
        accountFreeze.setUserId(userId);
        accountFreezeMapper.insert(accountFreeze);

        // 2、修改 account_tbl表 减钱
        accountMapper.deduct(userId,money);


    }

    @Override
    public boolean confirm(BusinessActionContext bac) {

        //  删除 account_freeze 表
            // 获取 xid
        String xid = bac.getXid();
        int i = accountFreezeMapper.deleteById(xid);

        return i == 1;
    }

    @Override
    public boolean cancel(BusinessActionContext bac) {

        // 获取 xid 查询 有没有 这条冻结数据
        String xid = bac.getXid();
        //String xid = RootContext.getXID();
        AccountFreeze accountFreeze = accountFreezeMapper.selectById(xid);
        if (accountFreeze == null){
           accountFreeze = new AccountFreeze();

            // 执行 空回滚逻辑     添加一条冻结数据 设置 money为0
            accountFreeze.setState(AccountFreeze.State.CANCEL);
            accountFreeze.setFreezeMoney(0);
            // 获取 新的 xid
            String newXid = RootContext.getXID();
            accountFreeze.setXid(newXid);
            accountFreeze.setUserId( bac.getActionContext("userId").toString());
            accountFreezeMapper.insert(accountFreeze);
            return true;
        }

        // 幂等性
        if (accountFreeze.getState() == AccountFreeze.State.CANCEL){
            return true;
        }


        // 1、修改 account——tbl 表 将钱 加回来
        accountMapper.refund(accountFreeze.getUserId(),accountFreeze.getFreezeMoney());

        // 2、修改 account_freeze 表 将 money修改成 0
        accountFreeze.setFreezeMoney(0);
        accountFreeze.setState(AccountFreeze.State.CANCEL);
        int i = accountFreezeMapper.updateById(accountFreeze);


        return i == 1;
    }
}
